package com.repair.filter;

import cn.hutool.json.JSONUtil;

import com.repair.exception.RepairException;
import com.repair.util.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class ExceptionHandler implements ErrorWebExceptionHandler {


    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable throwable) {
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Result result=null;
        if (throwable instanceof RepairException){
            RepairException movieException = (RepairException) throwable;
            result= Result.fail(movieException.getCode(), movieException.getMessage());
        }else{
            result=Result.fail(500,"系统错误");
        }
        String json = JSONUtil.parse(result).toString();
        return exchange.getResponse().writeWith(Mono.fromSupplier(()->{
            return exchange.getResponse().bufferFactory().wrap(json.getBytes());
        }));
    }
}
